package com.zl.learning.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MyClientHandler extends ChannelInboundHandlerAdapter {

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    private int count;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        executorService.execute(() -> sendMsg(ctx));
//        ByteBuf byteBuf = Unpooled.buffer(34);
//        byteBuf.writeIntLE(0xE005);
//        byteBuf.writeShortLE(26);
//        byteBuf.writeShortLE(0);
//        byteBuf.writeIntLE(2019114);
//        byteBuf.writeByte(1);
//        byteBuf.writeLongLE(460023225740955L);
//        byteBuf.writeLongLE(0L);
//        byteBuf.writeIntLE((int) (System.currentTimeMillis() / 1000));
//        byteBuf.writeByte(0);
//        ctx.writeAndFlush(byteBuf);
//        ctx.writeAndFlush("\r\n".getBytes());
    }

    private void sendMsg(ChannelHandlerContext ctx) {
        while (true) {
            sendMessage(ctx);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void sendMessage(ChannelHandlerContext ctx) {
        //使用客户端发送10条数据 hello,server 编号
        try {
            ByteBuf byteBuf = Unpooled.buffer(34);
            byteBuf.writeIntLE(0xE005);
            byteBuf.writeShortLE(26);
            byteBuf.writeShortLE(0);
            byteBuf.writeIntLE(2019114);
            byteBuf.writeByte(1);
            byteBuf.writeLongLE(460023225740955L);
            byteBuf.writeLongLE(0L);
            byteBuf.writeIntLE((int) (System.currentTimeMillis() / 1000));
            byteBuf.writeByte(0);
            ctx.writeAndFlush(byteBuf);
            ctx.writeAndFlush("\r\n".getBytes("UTF-8"));
            System.out.println("send msg");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        byte[] buffer = new byte[buf.readableBytes()];
        buf.readBytes(buffer);

        String message = new String(buffer, Charset.forName("utf-8"));
        System.out.println("客户端接收到消息=" + message);
        System.out.println("客户端接收消息数量=" + (++this.count));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
